/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.ucase.casemain.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.annotation.CaseChangeReportData;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.enums.DocumentKindEnum;
import com.icinfo.cloud.provider.common.enums.YesOrNoEnum;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.punish.approval.dto.AuditDetailDocumentQueryDto;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentStatusEnum;
import com.icinfo.cloud.provider.punish.common.electricsent.enums.DocumentSendStatusEnum;
import com.icinfo.cloud.provider.punish.common.electricsent.service.IDocumentSentFlowService;
import com.icinfo.cloud.provider.punish.common.sign.dto.SignAttachmentFileDto;
import com.icinfo.cloud.provider.punish.common.sign.dto.SignAttachmentFileSaveDto;
import com.icinfo.cloud.provider.punish.common.sign.dto.SignCaseSourceReceiveDto;
import com.icinfo.cloud.provider.punish.common.sign.dto.SignReceiveDto;
import com.icinfo.cloud.provider.punish.common.sign.vo.DocAttachmentsVo;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamDocumentInfo;
import com.icinfo.cloud.provider.punish.config.service.IConfigBusiParamDocumentInfoService;
import com.icinfo.cloud.provider.punish.csource.manage.mapper.CaseSourceDocumentRecordMapper;
import com.icinfo.cloud.provider.punish.csource.manage.mapper.CaseSourcePartyInfoMapper;
import com.icinfo.cloud.provider.punish.csource.manage.model.CaseSourceDocumentRecord;
import com.icinfo.cloud.provider.punish.csource.manage.model.CaseSourcePartyInfo;
import com.icinfo.cloud.provider.punish.csource.manage.service.ICaseSourceDocumentRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.AttachmentTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.HandleTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.PartiesReasonTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseAppendixRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseDocumentRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseAppendixRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseDocumentRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseAttachmentInfoVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseDocumentRecordDetailVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseHandlePersonRecordVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseMainInfoVo;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.mapper.CaseDocumentSendinfoConfirmMapper;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.model.CaseDocumentSendinfoConfirm;
import com.icinfo.cloud.workflow.common.annotation.WorkFlowRollAnnotation;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.common.web.Result;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.tools.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.ss.formula.functions.T;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 描述: 案件附件表-trj case_appendix_record 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年02月25日
 */
@Service
@Slf4j
@Transactional(rollbackFor = {Error.class, Exception.class})
public class CaseAppendixRecordServiceImpl extends MyBatisServiceSupport implements ICaseAppendixRecordService {


    @Resource
    private CaseAppendixRecordMapper caseAppendixRecordMapper;

    @Resource
    private CaseDocumentRecordMapper caseDocumentRecordMapper;
    @Resource
    private ICaseDocumentRecordService caseDocumentRecordService;
    @Resource
    private ICaseMainInfoService caseMainInfoService;
    @Resource
    private IConfigBusiParamDocumentInfoService configBusiParamDocumentInfoService;
    @Resource
    private ICasePartiesRecordService casePartiesRecordService;
    @Resource
    private IDocumentSentFlowService documentSentFlowService;
    @Resource
    private CaseDocumentSendinfoConfirmMapper caseDocumentSendinfoConfirmMapper;
    @Resource
    private CaseSourcePartyInfoMapper caseSourcePartyInfoMapper;
    @Resource
    private ICaseSourceDocumentRecordService caseSourceDocumentRecordService;
    @Resource
    private CaseSourceDocumentRecordMapper caseSourceDocumentRecordMapper;
    @Resource
    private ICaseHandlePersonRecordService caseHandlePersonRecordService;


    /**
     * 送达关联且需要当事人id的文书目录编码列表
     */
    public static List<String> sentRelatedNeedPartyIdDocumentKindCodeList;

    static {
        sentRelatedNeedPartyIdDocumentKindCodeList = new ArrayList<>();
        sentRelatedNeedPartyIdDocumentKindCodeList.add(Constant.STRING_KIND_CODE_SDHZ);
        sentRelatedNeedPartyIdDocumentKindCodeList.add(Constant.STRING_KIND_CODE_ZXQKHCJL);
        sentRelatedNeedPartyIdDocumentKindCodeList.add(Constant.STRING_KIND_CODE_XWTZS);
        sentRelatedNeedPartyIdDocumentKindCodeList.add(Constant.STRING_KIND_CODE_SQWTS);
        sentRelatedNeedPartyIdDocumentKindCodeList.add(Constant.STRING_KIND_CODE_SDDZQRS);
        sentRelatedNeedPartyIdDocumentKindCodeList.add(Constant.STRING_KIND_CODE_ZLGZTZS);
    }

    @Override
    public boolean saveCaseAppendixRecord(CaseAppendixRecord caseAppendixRecord) {
        try {
            UserDTO userDTO = UserUtil.getUserInfo();
            if (userDTO == null) {
                log.info("登录信息失效或未登录");
                return false;
            }
            caseAppendixRecord.setId(BaseUtil.createUid());
            caseAppendixRecord.setUploadTime(LocalDateTime.now());
            caseAppendixRecord.setUploadUserId(userDTO.getUserId().toString());
            caseAppendixRecord.setUploadUserName(userDTO.getRealName());
            caseAppendixRecord.setIsDelete(Constant.STRING_0);
            caseAppendixRecord.setAppendixStatus(Constant.STRING_1);
            int ret = caseAppendixRecordMapper.insertSelective(caseAppendixRecord);
            if (ret > 0) {
                return true;
            }
        } catch (Exception e) {
            log.info(e.getMessage());
            throw new BusinessException("保存附件失败");
        }
        return false;
    }

    @Override
    public List<DocAttachmentsVo> getDocLinkAttachments(AuditDetailDocumentQueryDto auditDetailDocumentQueryDto) {
        //如果是文书查询页面的查看文书按钮查询接口，则会出现caseId为空的情况（直通车文书未关联案件）
        if(Objects.isNull(auditDetailDocumentQueryDto.getCaseId())){
            log.warn("查询文书相关附件caseId为空！");
            return new ArrayList<>();
        }
        CaseMainInfoVo caseMainInfoVo = caseMainInfoService.getCaseMainInfo(auditDetailDocumentQueryDto.getCaseId());
        String handleType = caseMainInfoVo.getHandleType();
        List<DocAttachmentsVo> vos = new ArrayList<>();
        //查询文书种类
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(auditDetailDocumentQueryDto.getDocumentCatalogCode());
        String kindCode = configBusiParamDocumentInfo.getDocumentKindCode();

        Example example = new Example(CaseAppendixRecord.class);
        if ((StringUtils.isBlank(handleType) || !Constant.STRING_2.equals(handleType)) && !sentRelatedNeedPartyIdDocumentKindCodeList.contains(kindCode)) {
            example.createCriteria().andEqualTo("caseId", auditDetailDocumentQueryDto.getCaseId())
                    .andEqualTo("documentCatalogCode", auditDetailDocumentQueryDto.getDocumentCatalogCode())
                    .andEqualTo("isDelete", "0").andEqualTo("appendixStatus", "1");
        } else {
            example.createCriteria().andEqualTo("caseId", auditDetailDocumentQueryDto.getCaseId())
                    .andEqualTo("documentCatalogCode", auditDetailDocumentQueryDto.getDocumentCatalogCode())
                    .andEqualTo("isDelete", "0").andEqualTo("appendixStatus", "1")
                    .andEqualTo("partyId", auditDetailDocumentQueryDto.getPartyId());
        }

        List<CaseAppendixRecord> caseAppendixRecords = caseAppendixRecordMapper.selectByExample(example);
        String fg = ",";
        for (CaseAppendixRecord appendix : caseAppendixRecords) {
            // 多文件处理
            if (!appendix.getAppendixUrl().contains(fg)) {
                DocAttachmentsVo vo = new DocAttachmentsVo();
                vo.setAppendixTypeCode(appendix.getAppendixTypeId());
                vo.setAppendixType(AttachmentTypeEnum.getValueByCode(appendix.getAppendixTypeId()));
                vo.setAppendixName(appendix.getAppendixName());
                vo.setAppendixUrl(appendix.getAppendixUrl());
                vo.setId(appendix.getId());
                vo.setCreateUserName(appendix.getUploadUserName());
                vo.setCreateTime(appendix.getUploadTime());
                vo.setPartyId(appendix.getPartyId());
                vos.add(vo);
            } else {
                String[] urls = appendix.getAppendixUrl().split(fg);
                String[] name = appendix.getAppendixName().split(fg);
                for (int i = 0; i < urls.length; i++) {
                    DocAttachmentsVo vo = new DocAttachmentsVo();
                    vo.setAppendixTypeCode(appendix.getAppendixTypeId());
                    vo.setAppendixType(AttachmentTypeEnum.getValueByCode(appendix.getAppendixTypeId()));
                    if (name.length > 0 && urls.length == name.length) {
                        vo.setAppendixName(name[i]);
                    }
                    vo.setAppendixUrl(urls[i]);
                    vo.setId(appendix.getId());
                    vo.setCreateUserName(appendix.getUploadUserName());
                    vo.setCreateTime(appendix.getUploadTime());
                    vo.setPartyId(appendix.getPartyId());
                    vos.add(vo);
                }
            }
        }
        return vos;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @WorkFlowRollAnnotation
    @CaseChangeReportData
    public Map<String, Object> saveOfflineSignFile(SignReceiveDto signReceiveDto) {
        if (ObjectUtils.isEmpty(signReceiveDto)) {
            throw new BusinessException("未指定文书案件相关信息");
        }
        String caseId = signReceiveDto.getCaseId();
        if (ObjectUtils.isEmpty(caseId)) {
            throw new BusinessException("未指定案件id");
        }
        String documentCatalogCode = signReceiveDto.getDocCategoryCode();
        if (ObjectUtils.isEmpty(documentCatalogCode)) {
            throw new BusinessException("未指定文书目录编码");
        }
        String partyId = signReceiveDto.getPartyId();
        //增加送达当事人id处理
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
        String partiesReasonType = caseMainInfo.getCasePartiesReasonType();
        String handleType = caseMainInfo.getHandleType();

        //查询文书种类
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
        String kindCode = configBusiParamDocumentInfo.getDocumentKindCode();

        if (ObjectUtils.isEmpty(partyId)) {
            if (PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(partiesReasonType)
                    && !"GZSHZ".equals(kindCode)
            ) {
                throw new BusinessException("多当事人案件需指定当事人id");
            }
            // fixme 询问笔录和现场勘验确认暂时不传partyId
            if (Arrays.asList(DocumentKindEnum.DOC_KIND_DK2XWBL.getCode(),DocumentKindEnum.DOC_KIND_DK2XCKYJCBL.getCode()).contains(kindCode)){
                partyId = "";
            }else {
                Map<String, String> map = casePartiesRecordService.getCasePartyIdNameInfo(caseId);
                partyId = map.get("partyId");
            }

        }
        //如果传的文书记录ID不为空，则需要根据文书记录ID去查询
        CaseDocumentRecord caseDocumentRecord = null;
        if(StrUtil.isNotEmpty(signReceiveDto.getDocumentRecordId())&& !documentCatalogCode.contains(Constant.STRING_UNDERLINE)){
            caseDocumentRecord = caseDocumentRecordMapper.selectByPrimaryKey(signReceiveDto.getDocumentRecordId());
        }else {
            caseDocumentRecord = caseDocumentRecordService.getCaseDocumentRecord(caseId, documentCatalogCode, partyId);
        }
        CaseAppendixRecord caseAppendixRecord = new CaseAppendixRecord();
        int dr = 0;
        if (caseDocumentRecord != null) {
            caseAppendixRecord.setCaseStageCode(caseDocumentRecord.getCaseStageCode());
            caseAppendixRecord.setCaseStageName(caseDocumentRecord.getCaseStageName());
            caseAppendixRecord.setCaseLinkCode(caseDocumentRecord.getCaseLinkCode());
            caseAppendixRecord.setCaseLinkName(caseDocumentRecord.getCaseLinkName());
            caseDocumentRecord.setDocumentSignstampedStatus(DocumentStatusEnum.CONFIRM_END.getCode());
            //当文书为送达方式及地址确认书更新文书创建时间作为确认时间来使用,后续用于计算有效期限
            if (Constant.STRING_KIND_CODE_SDDZQRS.equals(kindCode)) {
                caseDocumentRecord.setDocumentCreateTime(LocalDateTime.now());
                //送达地址确认书确认时更新送达地址确认书表的状态为1
                Example updateExample = new Example(CaseDocumentSendinfoConfirm.class);
                updateExample.createCriteria().andEqualTo("caseId", caseDocumentRecord.getCaseId()).andEqualTo("partyId", caseDocumentRecord.getPartyId());
                CaseDocumentSendinfoConfirm caseDocumentSendinfoConfirm = new CaseDocumentSendinfoConfirm();
                caseDocumentSendinfoConfirm.setStatus(Constant.INTEGER_1);
                caseDocumentSendinfoConfirmMapper.updateByExampleSelective(caseDocumentSendinfoConfirm, updateExample);
            }
            dr = caseDocumentRecordMapper.updateByPrimaryKeySelective(caseDocumentRecord);
        }
        caseAppendixRecord.setAppendixTypeId("OFFLINE_SIGN_FILE");
        caseAppendixRecord.setCaseId(caseId);
        String prefix = signReceiveDto.getAppendixNamePrefix();
        String suffix = signReceiveDto.getAppendixNameSuffix();
        caseAppendixRecord.setAppendixName(prefix + Constant.STRING_POINT + suffix);
        caseAppendixRecord.setAppendixNamePrefix(prefix);
        caseAppendixRecord.setAppendixNameSuffix(suffix);
        caseAppendixRecord.setAppendixUrl(signReceiveDto.getDocUrl());
        caseAppendixRecord.setDocumentCatalogCode(documentCatalogCode);
        caseAppendixRecord.setUploadTime(LocalDateTime.now());
        caseAppendixRecord.setPartyId(partyId);//设置当事人id
        // 签字之后判断案件是否需要，更新案件状态
        // todo
        Map<String, Object> rs = new HashMap<>(8);
        if (saveCaseAppendixRecord(caseAppendixRecord) && dr == 1) {
            if (!ObjectUtils.isEmpty(partyId)) {
                if (Constant.STRING_2.equals(handleType) || sentRelatedNeedPartyIdDocumentKindCodeList.contains(kindCode)) {
                    rs.put("workSubId", partyId);
                } else {
                    rs.put("workSubId", null);
                }
            }
            rs.put("workId", caseId);
            rs.put("closeSignal", "CLOSE-TRIGGER-SIGNSTAMPED");
            if (!ObjectUtils.isEmpty(documentCatalogCode) && documentCatalogCode.contains(Constant.STRING_UNDERLINE)) {
                /*String tmpKindCode;
                if (documentCatalogCode.contains("SDHZBD1F5")) {
                    tmpKindCode = Constant.STRING_KIND_CODE_CFGZS;
                } else if (documentCatalogCode.contains("SDHZBD1F6")) {
                    tmpKindCode = Constant.STRING_KIND_CODE_CFGZSTZL;
                } else if (documentCatalogCode.contains("SDHZBD1F7")) {
                    //判断是否为简易处罚
                    tmpKindCode = Constant.STRING_KIND_CODE_CFJDS;
                    if (CaseTypeEnum.SIMPLE_PROCEDURE.getCode().equals(caseMainInfo.getCaseType())) {
                        tmpKindCode = Constant.STRING_KIND_CODE_JYCXCFJDS;
                    }
                } else if (documentCatalogCode.contains("SDHZ7B444")) {
                    tmpKindCode = Constant.STRING_KIND_CODE_BYCFJDS;
                } else if (documentCatalogCode.contains("SDHZC8650")) {
                    tmpKindCode = Constant.STRING_KIND_CODE_JDYJGZS;
                } else if (documentCatalogCode.contains("SDHZBD1F8")) {
                    tmpKindCode = Constant.STRING_KIND_CODE_XZCFCXJDS;
                } else if (documentCatalogCode.contains("SDHZBD3FG")) {
                    tmpKindCode = Constant.STRING_KIND_CODE_XZJDLXCGS;
                } else {
                    throw new BusinessException("未找到对应更新文书目录编码-saveOfflineSignFile");
                }
                List<ConfigBusiParamDocumentInfo> list = configBusiParamDocumentInfoService.getDocumentConfigInfoByDocumentKindCode(caseId,caseMainInfo,tmpKindCode);
                if(!ObjectUtils.isEmpty(list)){
                    documentCatalogCode = list.get(Constant.INTEGER_0).getDocumentCatalogCode();
                } else {
                    throw new BusinessException("未匹配文书目录编码信息-caseId:" + caseId + ",kindCode:" + tmpKindCode);
                }*/

                //查询送达回证配置
                ConfigBusiParamDocumentInfo detailByDocumentCatalogCode = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
                documentCatalogCode = detailByDocumentCatalogCode.getMatchSentDocumentCatalogCode();
                if (ObjectUtils.isEmpty(documentCatalogCode)) {
                    throw new BusinessException("未找到对应更新文书目录编码-saveOfflineSignFile");
                }

                //更新文书送达时间
                String sendStatus = DocumentSendStatusEnum.SEND_SUCCESS.getCode();
                CaseDocumentRecordQueryDto queryDto = new CaseDocumentRecordQueryDto();
                queryDto.setCaseId(caseId);
                queryDto.setRelateDocumentCatalogCode(documentCatalogCode);
                if (!HandleTypeEnum.MERGE_PUNISH.getCode().equals(handleType)) {
                    queryDto.setPartyId(partyId);
                }
                CaseDocumentRecordDetailVo vo = caseDocumentRecordService.getCaseDocumentRecordDetail(queryDto);
                if (ObjectUtils.isEmpty(vo)) {
                    throw new BusinessException("未找到文书记录-caseId:{" + caseId + "},documentCatalogCode:{" + documentCatalogCode + "}");
                }
                rs.put("closeSignal", "CLOSE-TRIGGER-SENT");

                String documentId = vo.getDocumentId();
                if (documentSentFlowService.checkDocumentIsAllSend(caseId, documentId)) {
                    caseDocumentRecordService.updateDocumentSentInfo(documentId, LocalDateTime.now(), sendStatus);
                }
            } else {
                List<String> list = new ArrayList<>();
                list.add("CFGZS");
                list.add("CFGZSTZL");
                list.add("CFJDS");
                list.add("BYCFJDS");
                list.add("DK2BYXZCFGZS");
                list.add("CLJDS");
                list.add("CLGZSTZL");
                if (list.contains(kindCode)) {
                    //取对应审批表
                    rs.put("closeSignal", "CLOSE-TRIGGER-SENT");
                }
            }

            rs.put("documentCatalogCode", documentCatalogCode);
        } else {
            throw new BusinessException("上传线下已签署文书时数据保存出现异常");
        }
        return rs;
    }

    /**
     * 【V1.0.0】描述：获取案件附件列表
     *
     * @param queryDto {@link CaseAttachmentInfoQueryDto}
     * @return {@link List< CaseAttachmentInfoVo >} 案件附件列表
     * @author xiangyuyu
     * @date 2022-02-27 09:49
     */
    @Override
    public List<CaseAttachmentInfoVo> getCaseAttachmentList(CaseAttachmentInfoQueryDto queryDto) {
        List<CaseAttachmentInfoVo> caseAttachmentInfoList = caseAppendixRecordMapper.selectCaseAttachmentList(queryDto);
        return caseAttachmentInfoList;
    }

    /**
     * 【V1.0.0】描述：根据唯一标识查询案件附件信息
     *
     * @param id 唯一标识
     * @return {@link CaseAttachmentInfoVo} 案件附件信息
     * @author xiangyuyu
     * @date 2022-02-27 09:49
     */
    @Override
    public CaseAttachmentInfoVo getCaseAttachmentInfo(String id) {
        log.info("getCaseAttachmentInfo start(id:+" + id + ")...");
        CaseAppendixRecord casePartiesLegalInfo = caseAppendixRecordMapper.selectByPrimaryKey(id);
        if (ObjectUtils.isEmpty(casePartiesLegalInfo)) {
            throw new BusinessException("未找到个人信息");
        }
        CaseAttachmentInfoVo vo = new CaseAttachmentInfoVo();
        BeanUtils.copyProperties(casePartiesLegalInfo, vo);
        log.info("getCaseAttachmentInfo end-vo:" + vo);
        return vo;
    }

    /**
     * 【V1.0.0】描述：删除案件关联附件
     *
     * @param id 唯一标识
     * @return {@link Result <String>} 删除结果
     * @author xiangyuyu
     * @date 2022-03-07 13:47
     */
    @Override
    public Result<String> removeCaseAttachment(String id) {
        if (ObjectUtils.isEmpty(id)) {
            return Result.error("请指定案件关联附件的主键id");
        }
        CaseAppendixRecord caseAppendixRecord = new CaseAppendixRecord();
        caseAppendixRecord.setId(id);
        caseAppendixRecord.setIsDelete(YesOrNoEnum.YES.getCode());
        caseAppendixRecordMapper.updateByPrimaryKeySelective(caseAppendixRecord);
        return Result.success("删除成功");
    }

    /**
     * 根据案件id与文书目录编码删除关联附件
     *
     * @param caseId
     * @param documentCatalogCode
     * @return
     * @author liyafeng
     * @date 2022/3/30
     */
    @Override
    public void removeCaseAppendixRecordByCaseIdAndCatalogCode(String caseId, String documentCatalogCode) {
        Map<String, Object> map = new HashMap<>();
        map.put("caseId", caseId);
        map.put("documentCatalogCode", documentCatalogCode);
        caseAppendixRecordMapper.deleteByCaseIdAndCatalogCode(map);
    }


    /**
     * 描述：获取案件相关附件列表
     *
     * @param queryDto {@link CaseAttachmentInfoQueryDto}
     * @return {@link List<CaseAttachmentInfoVo>} 案件相关附件列表
     * @author xiangyuyu
     * @date 2022-04-09 15:26
     */
    @Override
    public List<CaseAttachmentInfoVo> getCaseAttachmentInfoList(CaseAttachmentInfoQueryDto queryDto) {
        List<CaseAttachmentInfoVo> caseAttachmentInfoList = caseAppendixRecordMapper.selectCaseAttachmentList(queryDto);
        return caseAttachmentInfoList;
    }

    /**
     * 根据案件id、文书目录编码、当事人id删除关联附件
     *
     * @param caseId
     * @param docCatalogCode
     * @param partyId
     * @return
     * @author liyafeng
     * @date 2022/5/23
     */
    @Override
    public void removeCaseAppendixRecordByCaseIdAndCatalogCodeAndPartyId(String caseId, String docCatalogCode, String partyId) {
        Map<String, Object> map = new HashMap<>();
        map.put("caseId", caseId);
        map.put("documentCatalogCode", docCatalogCode);
        if (StringUtils.isNotBlank(partyId)) {
            map.put("partyId", partyId);
        }
        caseAppendixRecordMapper.deleteByCaseIdAndCatalogCode(map);
    }

    /**
     * 【V1.3.0】描述：根据环节编码撤回附件数据
     *
     * @return
     * @author tianrunjia
     * @date 2022-06-27
     */
    @Override
    public void recallCaseAppendixRecordByCaseLinkCode(String caseId, String caseLinkCode) {
        caseAppendixRecordMapper.updateRecallCaseAppendixRecordByCaseLinkCode(caseId, caseLinkCode);
    }

    /**
     * 上传线下已签署文书-案源
     *
     * @param signReceiveDto
     * @return {@link Map< Object, Object>}
     * @author liyafeng
     * @date 2022/8/18
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveOfflineSignFile(SignCaseSourceReceiveDto signReceiveDto) {
        if (ObjectUtils.isEmpty(signReceiveDto)) {
            throw new BusinessException("未指定文书案件相关信息");
        }
        String caseSourceId = signReceiveDto.getCaseSourceId();
       /* String caseId = signReceiveDto.getCaseId();
        if (ObjectUtils.isEmpty(caseId)) {
            throw new BusinessException("未指定案件id");
        }*/
        String documentCatalogCode = signReceiveDto.getDocCategoryCode();
        if (ObjectUtils.isEmpty(documentCatalogCode)) {
            throw new BusinessException("未指定文书目录编码");
        }
        String partyId = signReceiveDto.getPartyId();
        //增加送达当事人id处理
        /*CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
        String partiesReasonType = caseMainInfo.getCasePartiesReasonType();
        String handleType = caseMainInfo.getHandleType();*/
        Example example = new Example(CaseSourcePartyInfo.class);
        example.createCriteria().andEqualTo("status", Constant.STRING_1).andEqualTo("caseSourceId", signReceiveDto.getCaseSourceId());
        List<CaseSourcePartyInfo> caseSourcePartyInfos = caseSourcePartyInfoMapper.selectByExample(example);
        String partiesReasonType = Constant.STRING_1;
        if (null != caseSourcePartyInfos && caseSourcePartyInfos.size() > 1) {
            partiesReasonType = Constant.STRING_2;
        }
        //查询文书种类
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
        String kindCode = configBusiParamDocumentInfo.getDocumentKindCode();
        if (ObjectUtils.isEmpty(partyId)) {
            if (PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(partiesReasonType)
                    && !"GZSHZ".equals(kindCode)
            ) {
                throw new BusinessException("多当事人案件需指定当事人id");
            }
            //Map<String, String> map = casePartiesRecordService.getCasePartyIdNameInfo(caseId);
            //partyId = map.get("partyId");

        }
        CaseSourceDocumentRecord caseSourceDocumentRecord = caseSourceDocumentRecordService.getCaseDocumentRecord(signReceiveDto.getCaseSourceId(), documentCatalogCode, partyId);
        CaseAppendixRecord caseAppendixRecord = new CaseAppendixRecord();
        int dr = 0;
        if (caseSourceDocumentRecord != null) {
            caseAppendixRecord.setCaseStageCode(caseSourceDocumentRecord.getCaseStageCode());
            caseAppendixRecord.setCaseStageName(caseSourceDocumentRecord.getCaseStageName());
            caseAppendixRecord.setCaseLinkCode(caseSourceDocumentRecord.getCaseLinkCode());
            caseAppendixRecord.setCaseLinkName(caseSourceDocumentRecord.getCaseLinkName());
            caseSourceDocumentRecord.setDocumentSignstampedStatus(DocumentStatusEnum.CONFIRM_END.getCode());
            //当文书为送达方式及地址确认书更新文书创建时间作为确认时间来使用,后续用于计算有效期限
            if (Constant.STRING_KIND_CODE_SDDZQRS.equals(kindCode)) {
                caseSourceDocumentRecord.setDocumentCreateTime(LocalDateTime.now());
                //送达地址确认书确认时更新送达地址确认书表的状态为1
                /*Example updateExample = new Example(CaseDocumentSendinfoConfirm.class);
                updateExample.createCriteria().andEqualTo("caseId", caseDocumentRecord.getCaseId()).andEqualTo("partyId", caseDocumentRecord.getPartyId());
                CaseDocumentSendinfoConfirm caseDocumentSendinfoConfirm = new CaseDocumentSendinfoConfirm();
                caseDocumentSendinfoConfirm.setStatus(Constant.INTEGER_1);
                caseDocumentSendinfoConfirmMapper.updateByExampleSelective(caseDocumentSendinfoConfirm, updateExample);*/
            }
            caseSourceDocumentRecordMapper.updateByPrimaryKeySelective(caseSourceDocumentRecord);
        }
        caseAppendixRecord.setAppendixTypeId("OFFLINE_SIGN_FILE");
        caseAppendixRecord.setCaseId(caseSourceId);
        String prefix = signReceiveDto.getAppendixNamePrefix();
        String suffix = signReceiveDto.getAppendixNameSuffix();
        caseAppendixRecord.setAppendixName(prefix + Constant.STRING_POINT + suffix);
        caseAppendixRecord.setAppendixNamePrefix(prefix);
        caseAppendixRecord.setAppendixNameSuffix(suffix);
        caseAppendixRecord.setAppendixUrl(signReceiveDto.getDocUrl());
        caseAppendixRecord.setDocumentCatalogCode(documentCatalogCode);
        caseAppendixRecord.setUploadTime(LocalDateTime.now());
        caseAppendixRecord.setPartyId(partyId);//设置当事人id
        boolean flag = saveCaseAppendixRecord(caseAppendixRecord);
        if (flag) {
            dr = Constant.INTEGER_1;
        }
        return dr;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveSignAttachmentFile(SignAttachmentFileSaveDto saveDto) {
        if (ObjectUtils.isEmpty(saveDto)) {
            throw new BusinessException("未指定文书案件相关信息");
        }
        String caseId = saveDto.getCaseId();
        if (ObjectUtils.isEmpty(caseId)) {
            throw new BusinessException("未指定案件id");
        }
        String documentCatalogCode = saveDto.getDocCategoryCode();
        if (ObjectUtils.isEmpty(documentCatalogCode)) {
            throw new BusinessException("未指定文书目录编码");
        }
        String partyId = saveDto.getPartyId();
        //增加送达当事人id处理
        CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
        String partiesReasonType = caseMainInfo.getCasePartiesReasonType();

        //删除原来的签字捺印附件
        Example example = new Example(CaseAppendixRecord.class);
        Example.Criteria criteria = example.createCriteria();
        if (!PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(partiesReasonType)) {
            if(StringUtils.isBlank(partyId)) {
                Map<String, String> map = casePartiesRecordService.getCasePartyIdNameInfo(caseId);
                partyId = map.get("partyId");
            }
            criteria.andEqualTo("partyId", partyId);
        } else if (HandleTypeEnum.PART_PUNISH.getCode().equals(caseMainInfo.getHandleType())) {
            criteria.andEqualTo("partyId", partyId);
        } else {
            if(StringUtils.isBlank(partyId)) {
                Map<String, String> map = casePartiesRecordService.getCasePartyIdNameInfo(caseId);
                partyId = map.get("partyId");
            }
        }
        if (ObjectUtils.isEmpty(partyId)) {
            throw new BusinessException("当事人id不能为空");
        }
        //查询签字捺印附件
        criteria.andEqualTo("caseId", caseId).andEqualTo("documentCatalogCode", documentCatalogCode).andEqualTo("appendixTypeId", "SIGN_ATTACHMENT");
        //删除原来的签字捺印附件
        CaseAppendixRecord deleteRecord = new CaseAppendixRecord();
        deleteRecord.setIsDelete(Constant.STRING_1);
        caseAppendixRecordMapper.updateByExampleSelective(deleteRecord, example);

        CaseDocumentRecord caseDocumentRecord = caseDocumentRecordService.getCaseDocumentRecord(caseId, documentCatalogCode, partyId);
        if (ObjectUtils.isEmpty(caseDocumentRecord)) {
            throw new BusinessException("签字文书不存在");
        }
        List<SignAttachmentFileDto> signAttachmentFileDtoList = saveDto.getSignAttachmentFileDtoList();
        CaseAppendixRecord caseAppendixRecord = new CaseAppendixRecord();
        caseAppendixRecord.setCaseStageCode(caseDocumentRecord.getCaseStageCode());
        caseAppendixRecord.setCaseStageName(caseDocumentRecord.getCaseStageName());
        caseAppendixRecord.setCaseLinkCode(caseDocumentRecord.getCaseLinkCode());
        caseAppendixRecord.setCaseLinkName(caseDocumentRecord.getCaseLinkName());
        //设置当事人id
        caseAppendixRecord.setPartyId(partyId);
        caseAppendixRecord.setCaseId(caseId);
        if (ObjectUtil.isNotEmpty(signAttachmentFileDtoList) && signAttachmentFileDtoList.size() > 0) {
            for (SignAttachmentFileDto fileDto : signAttachmentFileDtoList) {
                String attachmentType=fileDto.getAttachmentType();
                String materialTypeId=Constant.STRING_1.equalsIgnoreCase(attachmentType) ? AttachmentTypeEnum.SIGN_ATTACHMENT_01.getCode():AttachmentTypeEnum.SIGN_ATTACHMENT_02.getCode();
                caseAppendixRecord.setAppendixTypeId(materialTypeId);
                String prefix = fileDto.getAppendixNamePrefix();
                String suffix = fileDto.getAppendixNameSuffix();
                caseAppendixRecord.setAppendixName(prefix + Constant.STRING_POINT + suffix);
                caseAppendixRecord.setAppendixNamePrefix(prefix);
                caseAppendixRecord.setAppendixNameSuffix(suffix);
                caseAppendixRecord.setAppendixUrl(fileDto.getDocUrl());
                caseAppendixRecord.setDocumentCatalogCode(documentCatalogCode);
                caseAppendixRecord.setUploadTime(LocalDateTime.now());
                saveCaseAppendixRecord(caseAppendixRecord);
            }
        }
        return 1;
    }

    /**
     * 根据案件id、文书目录编码、当事人id删除关联附件
     *
     * @param map 地图
     * @author shishengyao
     * @date 2022/11/18
     */
    @Override
    public void removeCaseAppendixRecordByAppendixTypeId(Map<String, Object> map) {
        if (caseMainInfoService.validateIsNeedPassPartyId(null,map.get("caseId")+"")) {
            map.put("partyId", map.get("partyId"));
        }
        caseAppendixRecordMapper.deleteByCaseIdAndCatalogCode(map);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<String> saveCaseAttachmentInfo(CaseStageAppendixSaveDto caseStageAppendixSaveDto) {
        List<CaseHandlePersonRecordVo> caseHandlePersonRecordList = caseHandlePersonRecordService.getCaseHandlePersonRecordListByCaseId(caseStageAppendixSaveDto.getCaseId());
        List<String> userIds = caseHandlePersonRecordList.stream().map(s->s.getHandlePersonId()).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(userIds) || !userIds.contains(UserUtil.getUserInfo().getUserId().toString())){
            throw new BusinessException("无权限操作附件");
        }
        List<AppendixRecordDto> appendixRecordDtos = caseStageAppendixSaveDto.getData();
        Map<String, Object> paramsMap = new HashMap<>(3);
        // 删除不存在id的附件信息
        paramsMap.put("caseId", caseStageAppendixSaveDto.getCaseId());
        paramsMap.put("caseStageCode", caseStageAppendixSaveDto.getCaseStageCode());
        paramsMap.put("ids", appendixRecordDtos.stream().map(AppendixRecordDto::getId).filter(ObjectUtil::isNotEmpty).distinct().collect(Collectors.toList()));
        caseAppendixRecordMapper.deleteByCaseIdAndCaseStageCodeNotInIds(paramsMap);
        appendixRecordDtos.forEach(e->{
            e.setCaseId(caseStageAppendixSaveDto.getCaseId());
            e.setCaseStageCode(caseStageAppendixSaveDto.getCaseStageCode());
            e.setCaseStageName(caseStageAppendixSaveDto.getCaseStageName());
            CaseAppendixRecord caseAppendixRecord = new CaseAppendixRecord();
            if(StringUtils.isBlank(e.getId())){
                BeanUtils.copyProperties(e, caseAppendixRecord);
                caseAppendixRecord.setUploadType(Constant.STRING_1);
                saveCaseAppendixRecord(caseAppendixRecord);
            }else{
                BeanUtils.copyProperties(e, caseAppendixRecord);
                caseAppendixRecordMapper.updateByPrimaryKeySelective(caseAppendixRecord);
            }
        });

        return Result.success("保存成功");
    }

    @Override
    public List<CaseAttachmentInfoVo> getCaseAttachments(CaseAppendixQueryDto caseAppendixQueryDto) {
        caseAppendixQueryDto.setIsDelete(Constant.STRING_0);
        List<CaseAttachmentInfoVo> caseAttachmentInfoList = caseAppendixRecordMapper.selectCaseAttachmentSortList(caseAppendixQueryDto);
        return caseAttachmentInfoList;
    }
}
